package com._5704.website.filter;

import com._5704.website.exception.WebsiteExceptionEnum;
import com._5704.website.shiro.JwtToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class JwtFilter extends BasicHttpAuthenticationFilter {
    /**
     * 桥梁？
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        System.out.println("-----------JwtFilter:isAccessAllowed-----------");
        //判断请求的请求头是否带上 "Token"
        if (isLoginAttempt(request, response)){
            //如果存在，则进入 executeLogin 方法执行登入，检查 token 是否正确
            try{
                executeLogin(request, response);
                return true;
            }catch(Exception e) {
                responseError(request, response);
            }
        }
        //如果请求头不存在 Token，则可能是执行登陆操作或者是游客状态访问，无需检查 token，直接返回 true
        return true;
    }

    /**
     * 对token检查
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response){
        System.out.println("-----------JwtFilter:executeLogin-----------");
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        JwtToken jwt = new JwtToken(token);
        //交给自定义的realm对象去登录，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwt);
        return true;

    }

    /**
     * 检查请求是否有token
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        System.out.println("-----------JwtFilter:isLoginAttempt-----------");

        HttpServletRequest req= (HttpServletRequest) request;
        String token=req.getHeader("token");
        System.out.println("token:" + token);
        System.out.println("token != null:" + (token != null));
//        System.out.println("!token.isEmpty():" + (!token.isEmpty()));
        if (token != null)
            return !token.isEmpty();
        return false;
    }

    /**
     * 处理错误
     * @param request
     * @param response
     * @throws IOException
     */
    private void responseError(ServletRequest request, ServletResponse response) {
        System.out.println("-----------responseError-----------");
        try {
//            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//            int status = httpServletResponse.getStatus();
            // 使用((HttpServletResponse) response).sendRedirect("/unauthorized/");
            // 无法处理post请求，使用如下方法
            request.getRequestDispatcher("/unauthorized").forward(request,response);
//            httpServletResponse.sendRedirect("/unauthorized");
//            httpServletResponse.sendError(0,WebsiteExceptionEnum.TOKEN_ERROR.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 必要的前置配置
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("-----------JwtFilter:preHandle-----------");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        res.setHeader("Access-control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            res.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);

    }

}
